<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2>个人设置</h2>
      <p>管理您的个人信息和偏好设置</p>
    </div>

    <el-tabs v-model="activeTab" class="profile-tabs">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="editMode = !editMode">
                {{ editMode ? '取消编辑' : '编辑信息' }}
              </el-button>
            </div>
          </template>

          <div class="profile-content">
            <!-- 头像部分 -->
            <div class="avatar-section">
              <el-avatar :size="100" :src="userInfo.avatar" class="user-avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="avatar-actions" v-if="editMode">
                <el-upload
                  :show-file-list="false"
                  :before-upload="handleAvatarUpload"
                  accept="image/*"
                >
                  <el-button size="small" type="primary">更换头像</el-button>
                </el-upload>
              </div>
            </div>

            <!-- 基本信息表单 -->
            <el-form
              ref="profileFormRef"
              :model="userInfo"
              :rules="profileRules"
              label-width="100px"
              class="profile-form"
              :disabled="!editMode"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userInfo.username" disabled />
              </el-form-item>

              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email" />
              </el-form-item>

              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="userInfo.nickname" />
              </el-form-item>

              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="userInfo.gender">
                  <el-radio value="male">男</el-radio>
                  <el-radio value="female">女</el-radio>
                  <el-radio value="other">其他</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="生日" prop="birthday">
                <el-date-picker
                  v-model="userInfo.birthday"
                  type="date"
                  placeholder="选择生日"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>

              <el-form-item label="身高(cm)" prop="height">
                <el-input-number
                  v-model="userInfo.height"
                  :min="100"
                  :max="250"
                  placeholder="请输入身高"
                />
              </el-form-item>

              <el-form-item label="体重(kg)" prop="weight">
                <el-input-number
                  v-model="userInfo.weight"
                  :min="30"
                  :max="200"
                  placeholder="请输入体重"
                />
              </el-form-item>

              <el-form-item label="个人简介" prop="bio">
                <el-input
                  v-model="userInfo.bio"
                  type="textarea"
                  :rows="3"
                  placeholder="介绍一下自己..."
                />
              </el-form-item>

              <el-form-item v-if="editMode">
                <el-button type="primary" :loading="saving" @click="saveProfile">
                  {{ saving ? '保存中...' : '保存' }}
                </el-button>
                <el-button @click="cancelEdit">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 偏好设置 -->
      <el-tab-pane label="偏好设置" name="preferences">
        <el-card class="profile-card">
          <template #header>
            <span>个人偏好</span>
          </template>

          <div class="preferences-content">
            <!-- 风格偏好 -->
            <div class="preference-section">
              <h4>风格偏好</h4>
              <el-checkbox-group v-model="preferences.styles">
                <el-checkbox value="casual">休闲</el-checkbox>
                <el-checkbox value="formal">正式</el-checkbox>
                <el-checkbox value="business">商务</el-checkbox>
                <el-checkbox value="sport">运动</el-checkbox>
                <el-checkbox value="party">派对</el-checkbox>
                <el-checkbox value="vintage">复古</el-checkbox>
                <el-checkbox value="street">街头</el-checkbox>
              </el-checkbox-group>
            </div>

            <!-- 颜色偏好 -->
            <div class="preference-section">
              <h4>颜色偏好</h4>
              <el-checkbox-group v-model="preferences.colors">
                <el-checkbox value="black">黑色</el-checkbox>
                <el-checkbox value="white">白色</el-checkbox>
                <el-checkbox value="gray">灰色</el-checkbox>
                <el-checkbox value="blue">蓝色</el-checkbox>
                <el-checkbox value="red">红色</el-checkbox>
                <el-checkbox value="green">绿色</el-checkbox>
                <el-checkbox value="yellow">黄色</el-checkbox>
                <el-checkbox value="pink">粉色</el-checkbox>
              </el-checkbox-group>
            </div>

            <!-- 场合偏好 -->
            <div class="preference-section">
              <h4>常用场合</h4>
              <el-checkbox-group v-model="preferences.occasions">
                <el-checkbox value="work">工作</el-checkbox>
                <el-checkbox value="daily">日常</el-checkbox>
                <el-checkbox value="date">约会</el-checkbox>
                <el-checkbox value="party">聚会</el-checkbox>
                <el-checkbox value="travel">旅行</el-checkbox>
                <el-checkbox value="exercise">运动</el-checkbox>
                <el-checkbox value="formal">正式场合</el-checkbox>
              </el-checkbox-group>
            </div>

            <div class="preference-actions">
              <el-button type="primary" :loading="savingPreferences" @click="savePreferences">
                {{ savingPreferences ? '保存中...' : '保存偏好' }}
              </el-button>
            </div>
          </div>
        </el-card>
      </el-tab-pane>

      <!-- 账户安全 -->
      <el-tab-pane label="账户安全" name="security">
        <el-card class="profile-card">
          <template #header>
            <span>账户安全</span>
          </template>

          <div class="security-content">
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="120px"
            >
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
                />
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>

              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :loading="changingPassword" @click="changePassword">
                  {{ changingPassword ? '修改中...' : '修改密码' }}
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { userAPI } from '@/api'

// 当前激活的标签页
const activeTab = ref('basic')

// 编辑模式
const editMode = ref(false)
const saving = ref(false)
const savingPreferences = ref(false)
const changingPassword = ref(false)

// 用户信息
const userInfo = reactive({
  id: null,
  username: '',
  email: '',
  nickname: '',
  avatar: '',
  gender: '',
  birthday: '',
  height: null,
  weight: null,
  bio: ''
})

// 原始用户信息（用于取消编辑时恢复）
const originalUserInfo = reactive({})

// 表单验证规则
const profileRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  nickname: [
    { max: 50, message: '昵称不能超过50个字符', trigger: 'blur' }
  ],
  height: [
    { type: 'number', min: 100, max: 250, message: '身高应在100-250cm之间', trigger: 'blur' }
  ],
  weight: [
    { type: 'number', min: 30, max: 200, message: '体重应在30-200kg之间', trigger: 'blur' }
  ]
}

// 偏好设置
const preferences = reactive({
  styles: [],
  colors: [],
  occasions: []
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const profileFormRef = ref()
const passwordFormRef = ref()

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await userAPI.getProfile()
    if (response.code === 200) {
      Object.assign(userInfo, response.data)
      Object.assign(originalUserInfo, response.data)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 获取用户偏好
const getUserPreferences = async () => {
  try {
    const response = await userAPI.getPreferences()
    if (response.code === 200) {
      // 处理偏好数据
      const prefs = response.data
      preferences.styles = prefs.filter(p => p.preference_type === 'style').map(p => p.preference_key)
      preferences.colors = prefs.filter(p => p.preference_type === 'color').map(p => p.preference_key)
      preferences.occasions = prefs.filter(p => p.preference_type === 'occasion').map(p => p.preference_key)
    }
  } catch (error) {
    console.error('获取用户偏好失败:', error)
  }
}

// 保存个人信息
const saveProfile = async () => {
  if (!profileFormRef.value) return

  try {
    await profileFormRef.value.validate()
    saving.value = true

    const response = await userAPI.updateProfile(userInfo)
    if (response.code === 200) {
      ElMessage.success('保存成功')
      editMode.value = false
      Object.assign(originalUserInfo, userInfo)
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  Object.assign(userInfo, originalUserInfo)
  editMode.value = false
}

// 头像上传
const handleAvatarUpload = async (file) => {
  const formData = new FormData()
  formData.append('avatar', file)

  try {
    const response = await userAPI.uploadAvatar(formData)
    if (response.code === 200) {
      userInfo.avatar = response.data.avatar
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(response.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }

  return false // 阻止默认上传行为
}

// 保存偏好设置
const savePreferences = async () => {
  try {
    savingPreferences.value = true

    // 构建偏好数据
    const preferenceData = [
      ...preferences.styles.map(style => ({
        preference_type: 'style',
        preference_key: style,
        preference_value: 'true',
        weight: 1
      })),
      ...preferences.colors.map(color => ({
        preference_type: 'color',
        preference_key: color,
        preference_value: 'true',
        weight: 1
      })),
      ...preferences.occasions.map(occasion => ({
        preference_type: 'occasion',
        preference_key: occasion,
        preference_value: 'true',
        weight: 1
      }))
    ]

    const response = await userAPI.updatePreferences(preferenceData)
    if (response.code === 200) {
      ElMessage.success('偏好设置保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存偏好失败:', error)
    ElMessage.error('保存偏好失败')
  } finally {
    savingPreferences.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true

    const response = await userAPI.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })

    if (response.code === 200) {
      ElMessage.success('密码修改成功')
      // 清空表单
      Object.assign(passwordForm, {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    console.error('密码修改失败:', error)
    ElMessage.error('密码修改失败')
  } finally {
    changingPassword.value = false
  }
}

// 页面初始化
onMounted(() => {
  getUserInfo()
  getUserPreferences()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-header {
  margin-bottom: 24px;
}

.profile-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.profile-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.profile-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-card {
  border: none;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-content {
  display: flex;
  gap: 40px;
}

.avatar-section {
  flex-shrink: 0;
  text-align: center;
}

.user-avatar {
  margin-bottom: 16px;
  border: 3px solid #f0f0f0;
}

.avatar-actions {
  margin-top: 12px;
}

.profile-form {
  flex: 1;
  max-width: 600px;
}

.preferences-content {
  max-width: 800px;
}

.preference-section {
  margin-bottom: 32px;
}

.preference-section h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.preference-section .el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.preference-section .el-checkbox {
  margin-right: 0;
}

.preference-actions {
  padding-top: 24px;
  border-top: 1px solid #eee;
}

.security-content {
  max-width: 500px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
    gap: 24px;
  }

  .avatar-section {
    align-self: center;
  }

  .preference-section .el-checkbox-group {
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .profile-container {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .preference-section .el-checkbox-group {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
